<?php
// 1903010328 查票
$loginPath = "../login.html";
include "../inc/log/session.php";
// 1903010328 有无上传错误
if ($_FILES["picfile"]["error"] > 0) {
	# 有上传错误
	echo <<<end
	<script>
	alert("上传失败，请稍后再试！")
	history.back();
	</script>
end;
    exit();
}
	// 1903010328 判断上传的格式  设置必须为gif或png文件   
if ($_FILES["picfile"]["type"] != "image/gif" and $_FILES["picfile"]["type"] !='image/png') {
	echo <<<end
	<script>
	alert("上传格式错误，请稍后再试！")
	history.back();
	</script>
end;
    exit();
}
// 1903010328 判断上传大小 (#设置文件大小不能超过100KB)
if ($_FILES["picfile"]["size"] > 102400) {
	echo <<<end
	<script>
	alert("文件大小不能超过100KB，请稍后再试！")
	history.back();
	</script>
end;
    exit();
}


// 1903010328 设置文件的保存信息：目录、文件名
$fileName = md5(time());
$subFolder = date("Ymd")."/";
$saveName = $subFolder.$fileName;
$pathName = "../inc/portrait/".$subFolder.$fileName;
// 1903010328 检查：目标文件是否已经存在，若已存在，就不能移动
if (file_exists($pathName)) {
	# 若存在就退出
	echo <<<end
	<script>
	alert("上传失败，请稍后再试！")
	history.back();
	</script>
end;
}
// 1903010328 检查：指定的目录是否已经存在，若不存在，创建目录
if (!file_exists("../inc/portrait/".$subFolder)) {
	# 若不存在创建目录
	mkdir("../inc/portrait/".$subFolder);
}
// 1903010328 移动到指定位置
if (move_uploaded_file($_FILES["picfile"]["tmp_name"], $pathName)){
	echo "上传成功";

include "../inc/data/conn.php";
// 1903010328更新用户头像字段的值
	
	// 1903010328 设置sql字符串
	if($_SESSION["sf"] == "student"){
		$old= "select stupic from mamx_stu where stuid= ?";
		// 学生
        $sql ="update mamx_stu
               set stupic = '$saveName'
               where stuid ={$_SESSION['id']}";
	}else{
		$old= "select tepic from mamx_teacher where teid= ?";
       // 老师
        $sql ="update mamx_teacher
               set tepic = '$saveName'
               where teid ={$_SESSION['id']}";
	}
	if ($stmt = $conn -> prepare($old)) {
		$id = $_SESSION['id'];
		$stmt -> bind_param('i',$id);
		$stmt -> execute();
		$stmt -> bind_result($uPic);
		$stmt -> store_result();
	}
	// 执行
	$re = $conn  -> query($sql);
	// 判断
	if($conn -> affected_rows == 1){
		$stmt -> fetch();
		unlink("../inc/portrait/".$uPic);
		// 更新成功
		// 1903010328 回收旧头像
		$_SESSION["uPic"] = $saveName;
		 echo <<<END
      <script type="text/javascript">
       alert("{$_SESSION["name"]},头像更新成功！");
       location.href="../index.php";
      </script>
END;
	}else{
        // 更新失败
        // 1903010328 回收新头像
        echo <<<END
      <script type="text/javascript">
       alert("头像更新失败,请重试！");
       history.back();
      </script>
END;
	}
}
else{
	// 移动失败
	echo <<<END
      <script type="text/javascript">
       alert("头像上传失败，请重试！！");
       history.back();
      </script>
END;
}
?>